const jsonServer = require("json-server");
const $db = require("./db"); // db.json。或返回db.json数据格式的，db.js文件
const server = jsonServer.create();
const middlewares = jsonServer.defaults();
const router = jsonServer.router($db);

// 获取post参数
const getParams = (req) => {
  return new Promise((resolve, reject) => {
    let data = "";
    req.on("data", (chunk) => {
      data += chunk;
    });
    req.on("end", () => {
      // 将JSON字符串解析成对象
      data = JSON.parse(data);
      resolve(data);
    });
  });
};

let USERNAME = "";
const JwtToken = "Xfw432hFes";

// Set default middlewares (logger, static, cors and no-cache)
server.use(middlewares);

server.get("/echo", (req, res) => {
  res.jsonp(req.query);
});

server.get("/me", (req, res) => {
  const { authorization } = req.headers;

  if (authorization === `Bearer ${JwtToken}`) {
    res.status(200).send({
      name: USERNAME,
      id: "1",
      email: "1720557879@.com",
      title: "",
      organization: "",
      token: JwtToken,
    });
  } else {
    res.status(401).send({
      message: "登录失效",
    });
  }
});

server.post("/login", (req, res) => {
  getParams(req).then((params) => {
    const { username, password } = params;
    USERNAME = username;
    if (password === "123456") {
      res.status(200).send({
        status: 200,
        data: {
          name: username,
          id: "1",
          email: "1720557879@.com",
          title: "",
          organization: "",
          token: JwtToken,
        },
        message: "登录成功",
      });
    } else {
      res.status(409).send({ message: "账号或密码错误！" });
    }
  });
});

server.post("/register", (req, res) => {
  getParams(req).then((params) => {
    const { username, password } = params;
    USERNAME = username;
    res.status(200).send({
      status: 200,
      data: {
        name: username,
        id: "1",
        email: "1720557879@.com",
        title: "",
        organization: "",
        token: "Xfw432hFes",
      },
      message: "注册成功",
    });
  });
});

server.use((req, res, next) => {
  if (req.method === "POST") {
    req.body.createdAt = Date.now();
  }
  // Continue to JSON Server router
  next();
});

server.use((req, res, next) => {
  const { authorization } = req.headers;

  if (authorization === `Bearer ${JwtToken}`) {
    next();
  } else {
    res.status(401).send({
      message: "登录失效",
    });
  }
});
// Use default router
server.use(router);
// To handle POST, PUT and PATCH you need to use a body-parser
server.use(jsonServer.bodyParser);

server.listen(4001, () => {
  console.log("JSON Server is running at 4001");
});
